package com.wys.mall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.cbor.Jackson2CborDecoder;

import javax.annotation.PostConstruct;

/**
 * 消息队列配置
 * @Package com.wys.mall.order.config
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-07-1010:03
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
@Configuration
public class RabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 将保存为序列化的内容转化为json格式
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制rabbitTemplate
     * RabbitConfig在创建完成后调用此方法
     *
     * 消费端确认
     *  1、自动回复，但会丢失消息
     */
    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * @param correlationData 消息唯一关联数据
             * @param ack 是否成功还是失败
             * @param cause 失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("correlationData==" + correlationData);
                System.out.println("ack==" + ack);
                System.out.println("cause==" + cause);
            }
        });

        /**
         * 只有消息没有到达队列才回调
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * @param message 失败消息
             * @param replyCode 失败码
             * @param replyText 回复内容
             * @param exchange 发送的交换机
             * @param routingKey 交换机key
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("fail message==" + message);
                System.out.println("replyCode" + replyCode);
                System.out.println("exchange==" + exchange);
                System.out.println("routingKey==" + routingKey);
            }
        });
    }
}
